/*
循环神经网络层头文件
定义RNN层的接口和数据结构
支持序列到序列的建模任务
*/
#ifndef RECURRENT_LAYER_H
#define RECURRENT_LAYER_H

#include "Macros.h"
#include "../../common/include/Layer.h"
#include "../../common/include/ActivationFunction.h"
#include "../../common/include/LossFunction.h"
#include "../../common/include/Tensor.h"
#include <string>
#include <vector>
#include <memory>

using namespace std;
using namespace UserDefinedTensor;

class RecurrentLayer : public Layer {
public:
    RecurrentLayer(int layerIndex, int inputSize, int hiddenSize, int outputSize, 
                   const string& activationName = "tanh", const string& lossName = "mse");
    ~RecurrentLayer();

    // 状态管理
    void resetState();
    void setHiddenState(const Tensor<double, 1>& state);
    const Tensor<double, 1>& getHiddenState() const;
    
    // 前向传播
    Tensor<double, 1> forward(const Tensor<double, 1>& input);
    
    // 反向传播
    void backward(const Tensor<double, 1>& target, double learningRate = 0.01);

    // 梯度更新
    void updateWeights(double learningRate, double momentum);
    void updateBiases(double learningRate, double momentum);
    
    // 参数获取
    const Tensor<double, 2>& getInputWeights() const;
    const Tensor<double, 2>& getHiddenWeights() const;
    const Tensor<double, 2>& getOutputWeights() const;
    const Tensor<double, 1>& getHiddenBiases() const;
    const Tensor<double, 1>& getOutputBiases() const;
    
    // 工具函数
    void print() const;
    void setLearningRate(double learningRate);

private:
    int inputSize;
    int hiddenSize;
    int outputSize;
    double learningRate;
    
    // 权重矩阵
    Tensor<double, 2> Wxh;  // 输入到隐藏层的权重
    Tensor<double, 2> Whh;  // 隐藏层到隐藏层的权重
    Tensor<double, 2> Why;  // 隐藏层到输出层的权重
    
    // 偏置向量
    Tensor<double, 1> bh;   // 隐藏层偏置
    Tensor<double, 1> by;   // 输出层偏置
    
    // 状态和缓存
    Tensor<double, 1> hiddenState;     // 当前隐藏状态
    Tensor<double, 1> lastHiddenState;  // 上一个隐藏状态
    Tensor<double, 1> inputCache;        // 输入缓存
    Tensor<double, 1> outputCache;      // 输出缓存
    
    // 梯度缓存
    Tensor<double, 2> dWxh;  // Wxh的梯度
    Tensor<double, 2> dWhh;  // Whh的梯度
    Tensor<double, 2> dWhy;  // Why的梯度
    Tensor<double, 1> dbh;   // bh的梯度
    Tensor<double, 1> dby;   // by的梯度
    
    unique_ptr<ActivationFunction<double, 1>> activation;
    unique_ptr<LossFunction> loss;
};

#endif // RECURRENT_LAYER_H